package com.hk.Mgr.web.controller.app.yingmi;

import com.hk.api.ProcessAPI;
import com.hk.api.ValidateService;
import com.hk.app.utils.YingmiOpenAPI;
import com.hk.base.BaseCtrl;
import com.hk.commons.ResultCode;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.utils.IPUtil;
import com.hk.commons.utils.TerminalTypeEnum;
import com.hk.commons.utils.UserOccupationEnum;
import com.hk.commons.utils.sys.MapHelper;
import com.hk.commons.vo.JsonResult;
import com.hk.commons.vo.yingmi.*;
import com.hk.service.sys.ISysUser;
import com.hk.yingmi.YingmiOpenAPIConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能描述 券商相关
 * 创建人 luocheng
 * 创建时间2017/9/22.
 */
@Controller
@RequestMapping(value = BaseCtrl.App + "/yingmiAPI/broker")
public class BrokerController {

    private Logger logger = LoggerFactory.getLogger(BrokerController.class);

    @Autowired
    private ISysUser sysUser;

    @Autowired
    private YingmiOpenAPI openAPI;

    @Autowired
    ValidateService validateService;

    /**
     * 01-获取订单
     * @param request
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getBrokerOrders", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public JsonResult getFundOrders(HttpServletRequest request, @RequestBody GetFundListReq req) {
        return null;
    }

    /**
     * 02-获取在途订单
     * @param request
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getProcessingBrokerOrders", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public JsonResult getProcessingFundOrders(HttpServletRequest request, @RequestBody GetProcessingFundOrdersReq req) {
        return null;
    }

    /**
     * 03-获取仍有效的订单
     * @param request
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getBrokerShares", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public JsonResult getFundShare(HttpServletRequest request, @RequestBody GetFundShareReq req) {
        return null;
    }

    /**
     * A-获取基金信息接口
     * @param request
     * @param fundCode
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getFundInfo", method = RequestMethod.GET)
    public JsonResult getFundInfo(HttpServletRequest request, String fundCode) {
        ProcessAPI api = (jsonResult, validate) -> {

            Map<String, String> params = new HashMap<String, String>();
            params.put("fundCode", fundCode);

            logger.info("parm Map = {}", params);
            String jsonResp = openAPI.sslGet_ByMap(YingmiOpenAPIConstant.PRODUCT_GET_FUND_INFO, params, null);
            logger.info("result = {}", jsonResp);
            openAPI.processJsonResult(jsonResult, jsonResp);
        };

        return api.process(request);
    }

    /**
     * B-获取券商资管信息接口
     * https://doc.yingmi.cn/pages/viewpage.action?pageId=8357288
     * @param request
     * @param fundCode
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getQszgInfo", method = RequestMethod.GET)
    public JsonResult getQszgInfo(HttpServletRequest request, String fundCode) {
        ProcessAPI api = (jsonResult, validate) -> {

            Map<String, String> params = new HashMap<String, String>();
            params.put("fundCode", fundCode);

            logger.info("parm Map = {}", params);
            String jsonResp = openAPI.sslGet_ByMap(YingmiOpenAPIConstant.PRODUCT_GET_QSZG_INFO, params, null);
            logger.info("result = {}", jsonResp);
            openAPI.processJsonResult(jsonResult, jsonResp);
        };

        return api.process(request);
    }

    /**
     * C-获取投资者信息
     * @param accountId 投资者的盈米账户ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/investorInfo", method = RequestMethod.GET)
    public JsonResult getUserInfo(@RequestParam(value = "accountId") String accountId) {
        JsonResult jsonResult = new JsonResult();
        Map<String, Object> userMap = new HashMap<>();
        List<InvestorInfoModel> userOccupationList = new ArrayList<>();

        validateService.check("accountId", accountId);

        SysUser user = sysUser.getByAccountId(accountId);

        if(user == null) {
            jsonResult.result = "无效的accountId";
            jsonResult.resultCode = ResultCode.FAILED.getCode();
            jsonResult.msg = ResultCode.FAILED.getMsg();
            return jsonResult;
        }

        for (UserOccupationEnum s : UserOccupationEnum.values()) {
            userOccupationList.add(new InvestorInfoModel(s.getCode(), s.getValue()));
        }

        userMap.put("realName", user.getRealName().toString());//真实姓名
        userMap.put("identity", user.getEncryptID(user.getIdentity().toString()));//身份证号码
        userMap.put("userOccupation", userOccupationList);//用户职业
        jsonResult.result = userMap;
        jsonResult.resultCode = ResultCode.SUCC.getCode();
        jsonResult.msg = ResultCode.SUCC.getMsg();

        return jsonResult;
    }

    /**
     * D-投资者信息录入
     * @param request
     * @param getInvestorInfoReq
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/account/adequacy", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public JsonResult estimateBuyFundFee(HttpServletRequest request, @RequestBody GetInvestorInfoReq getInvestorInfoReq) {

        ProcessAPI api;
        api = (jsonResult, validate) -> {
            validateService.checkFieldAndPrepare("accountId", getInvestorInfoReq.getAccountId());

            SysUser user = sysUser.getByAccountId(getInvestorInfoReq.getAccountId());
            if(user == null) {
                jsonResult.result = "accountId 不合法.";
                jsonResult.resultCode = ResultCode.FAILED.getCode();
                jsonResult.msg = ResultCode.FAILED.getMsg();
                return ;
            }

            //较验必要字段 值非空
            validate.checkFieldAndPrepare("address", getInvestorInfoReq.getAddress());
            getInvestorInfoReq.setAddress(getInvestorInfoReq.getAddress());//地址
            validate.checkFieldAndPrepare("career", getInvestorInfoReq.getCareer());
            getInvestorInfoReq.setCareer(getInvestorInfoReq.getCareer());//用户职业

            //实际控制投资者信息的情况
            if(getInvestorInfoReq.getInvestorUserType().equals("1")) {
                getInvestorInfoReq.setInvestorName(user.getRealName());
                getInvestorInfoReq.setInvestorIdentityNo(user.getIdentity());

            } else if(getInvestorInfoReq.getInvestorUserType().equals("0")) {
                validate.checkFieldAndPrepare("investorName", getInvestorInfoReq.getInvestorName());
                getInvestorInfoReq.setInvestorName(getInvestorInfoReq.getInvestorName());
                validate.checkFieldAndPrepare("investorIdentityNo",getInvestorInfoReq.getInvestorIdentityNo());
                getInvestorInfoReq.setInvestorIdentityNo(getInvestorInfoReq.getIdentityNo());
            }

            //投资收益人信息的情况
            if(getInvestorInfoReq.getBeneficiaryType().equals("1")) {
                getInvestorInfoReq.setBeneficiaryName(user.getRealName());
                getInvestorInfoReq.setBeneficiaryIdentityNo(user.getIdentity());

            } else if(getInvestorInfoReq.getBeneficiaryType().equals("0")) {
                validate.checkFieldAndPrepare("beneficiaryName", getInvestorInfoReq.getBeneficiaryName());
                getInvestorInfoReq.setBeneficiaryName(getInvestorInfoReq.getBeneficiaryName());
                validate.checkFieldAndPrepare("beneficiaryIdentityNo", getInvestorInfoReq.getBeneficiaryIdentityNo());
                getInvestorInfoReq.setBeneficiaryIdentityNo(getInvestorInfoReq.getBeneficiaryIdentityNo());
            }

            //Other Field
            getInvestorInfoReq.setAccountId(getInvestorInfoReq.getAccountId());
            getInvestorInfoReq.setBrokerUserId(user.getName());
            getInvestorInfoReq.setAccountName(user.getRealName());
            getInvestorInfoReq.setIdentityNo(user.getIdentity());
            getInvestorInfoReq.setTerminalIP(IPUtil.getIpAddr(request));
            getInvestorInfoReq.setTerminalType(TerminalTypeEnum.MOBILE_APP.getCode());//终端信息移动App
            getInvestorInfoReq.setTerminalInfo(IPUtil.getUserAgent(request));//用户终端的相关信息
            getInvestorInfoReq.setReferenceNo(user.getName() + System.currentTimeMillis());

            Map<String, String> parMap = MapHelper.transBean2Map(getInvestorInfoReq);

            logger.info("parm Map = {}", parMap);
            String result = openAPI.sslPost(YingmiOpenAPIConstant.ACCOUNT_ADEQUACY, parMap);
            logger.info("result = {}", result);
            openAPI.processJsonResult(jsonResult,result);
        };

        return api.process(request);
    }

}
